var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
// 引入jwt
// const JWT = require('./utils/jwt');
const cors = require("cors")
const dotenv = require("dotenv") // dotenv 包以访问 .env 文件
const { sequelize } = require("./models");
dotenv.config()
const userRoutes = require("./routes/userRoutes");
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(cors());
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// 在路由之前同步数据库
const isResetData = process.env.IsResetData === 'true';
sequelize
  .sync({ force: isResetData }) // force: true 会删除表并重新创建，生产环境慎用
  .then(() => {
    console.log("数据库和表已同步！!");
    // 运行种子文件
    const { exec } = require("child_process");
    exec("npx sequelize-cli db:seed:all", (error, stdout, stderr) => {
      if (error) {
        console.error("添加初始数据失败:", error);
        return;
      }
      console.log("Seeders executed successfully:", stdout);
    });
  })
  .catch((err) => {
    console.error("无法同步数据库:", err);
  });
// 在路由之前，先进行token验证
// app.use((req, res, next)=> {
  
// })
app.use("/api", userRoutes);


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
